package com.xiyu.service.repository.sales;

import com.xiyu.service.model.customer.info.CustomerInfoFetcher;
import com.xiyu.service.model.sales.SalesOrderFetcher;
import com.xiyu.service.vo.sales.SalesPageQueryInput;
import com.xiyu.service.model.sales.SalesOrder;
import com.xiyu.service.model.sales.SalesOrderTable;
import org.babyfish.jimmer.spring.repository.JRepository;
import org.babyfish.jimmer.Page;
import org.springframework.util.StringUtils;
import java.util.Optional;

public interface SalesOrderRepository extends JRepository<SalesOrder, Long> {
    SalesOrderTable salesOrderTable = SalesOrderTable.$;

    default Page<SalesOrder> pageQuery(SalesPageQueryInput inputVO){
        return sql().createQuery(salesOrderTable)
                .whereIf(StringUtils.hasText(inputVO.getSalesNo()), () -> salesOrderTable.salesNo().like(inputVO.getSalesNo()))
                .orderBy(salesOrderTable.id().desc())
                .select(salesOrderTable.fetch(SalesOrderFetcher.$.allTableFields().customer(CustomerInfoFetcher.$.customerNo().name())))
                .fetchPage(inputVO.getPageNo() - 1, inputVO.getPageSize());
    }

    default Optional<SalesOrder> findDetailById(Long id){
        return sql().createQuery(salesOrderTable)
                .where(salesOrderTable.id().eq(id))
                .select(salesOrderTable.fetch(SalesOrderFetcher.$.allTableFields().customer(CustomerInfoFetcher.$.customerNo().name())))
                .fetchOptional();
    }

    default void updateStatus(Long id, Integer status){
        sql().createUpdate(salesOrderTable)
                .where(salesOrderTable.id().eq(id))
                .set(salesOrderTable.status(), status)
                .execute();
    }


}